﻿// ===============================================================================
// Copyright(c) 2007-2020 西安交通信息投资营运有限公司 版权所有
// ===============================================================================

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using XCI.Core;
using XCI.Extensions;
using XCI.Sys.Filter;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows;
using XCI.Helper;

namespace XCI.Sys.Forms
{
    /// <summary>
    /// 系统角色管理
    /// </summary>
    [FormCaption("系统角色管理")]
    public partial class FrmRoleManager : BaseForm
    {
        private readonly bool allowSelect = SysApp.Permit("sys.role.select");
        private readonly bool allowInsert = SysApp.Permit("sys.role.insert");
        private readonly bool allowUpdate = SysApp.Permit("sys.role.update");
        private readonly bool allowDelete = SysApp.Permit("sys.role.delete");
        private readonly bool allowExport = SysApp.Permit("sys.role.export");
        private readonly bool allowAuthorize = SysApp.Permit("sys.role.authorize");

        public FrmRoleManager()
        {
            InitializeComponent();
            gridControl.ModelType = typeof(SysRole);
        }

        /// <summary>
        /// 加载首页数据
        /// </summary>
        private Task LoadFirstPageAsync()
        {
            return Mutex.EndAsync(() => gridControl.LoadFirstPageAsync());
        }

        private void ShowEditForm(EditFormArgs param)
        {
            var editForm = new FrmRoleEdit(param);
            editForm.ShowDialogOk(async () => await gridControl.LoadAsync());
        }

        private async void FrmRoleManager_Load(object sender, EventArgs e)
        {
            Mutex.Begin(() => statusCombo.SelectedIndex = 0);
            await filterLayoutControl.BindingDataAsync();
            await LoadFirstPageAsync();
        }

        private void btnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm(EditFormArgs.Create());
        }

        /// <summary>
        /// 修改事件
        /// </summary>
        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm(EditFormArgs.Edit(gridControl.SelectedId));
        }

        /// <summary>
        /// 复制事件
        /// </summary>
        private async void btnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBoxHelper.ShowWarnYesNo("确定要复制选中的数据吗?") != System.Windows.Forms.DialogResult.Yes) return;
            await SysRoleService.Instance.CopyAsync(gridControl.SelectedId);
            await gridControl.LoadAsync();
        }

        /// <summary>
        /// 删除事件
        /// </summary>
        private async void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            await gridControl.DeleteAsync();
        }

        private async void btnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var filter = gridControl.GetFilter();
            await App.Excel.ExportFileDialogAsync((path, fields) => SysRoleService.Instance.ExportAsync(path, filter as SysRoleFilter), "系统角色列表", this);
        }

        private void BtnAuthorize_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new FrmRoleAuthorize((SysRole)gridControl.Selected).ShowDialogOk(async () => await gridControl.LoadAsync());
        }

        private async void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            await SysRoleService.Instance.RefreshCacheAsync();
            await gridControl.LoadAsync();
            MessageBoxHelper.ShowMessage("缓存刷新成功");
        }

        private void btnProperty_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridControl.InvokeRowDoubleClick();
        }

        private void GridControl_LoadData(object sender, LoadDataEventArgs e)
        {
            e.Task = async () => await SysRoleService.Instance.SelectPageListAsync(e.Filter as SysRoleFilter);
        }

        private void GridControl_DetectFilter(object sender, DetectFilterEventArgs e)
        {
            e.Filter = App.ContainerData.GetModel(layoutGroupFilter, new SysRoleFilter());
        }

        private void GridControl_DeleteData(object sender, DeleteDataEventArgs e)
        {
            e.Task = () => SysRoleService.Instance.DeleteAsync(gridControl.SelectedIds);
        }

        private void GridControl_RowDoubleClick(object sender, EventArgs e)
        {
            new FrmRoleDetails(gridControl).ShowDialogOk();
        }

        private void GridControl_RowSelectionChanged(object sender, EventArgs e)
        {
            btnNew.Enabled = allowInsert;
            btnEdit.Enabled = gridControl.HasSingleSelected && allowUpdate;
            btnCopy.Enabled = gridControl.HasSingleSelected && allowInsert;
            btnDelete.Enabled = gridControl.HasSelected && allowDelete;
            btnAuthorize.Enabled = gridControl.HasSelected && allowAuthorize;
            btnExport.Enabled = gridControl.HasData && allowExport;
            btnProperty.Enabled = gridControl.HasSingleSelected;
            btnSearch.Enabled = allowSelect;
        }

        private async void RepositoryEditStatus_CheckedChanged(object sender, EventArgs e)
        {
            var edit = gridView.ActiveEditor;
            var col = gridView.FocusedColumn;
            if (col.FieldName.Equals(nameof(SysRole.Status)))
            {
                await SysRoleService.Instance.UpdateStatusAsync(gridControl.SelectedId, edit.EditValue.ToBool());
            }
        }

        private async void editName_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == R.EnterKey) await LoadFirstPageAsync();
        }

        private async void statusCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            await LoadFirstPageAsync();
        }

        private async void departmentTreeList_EditValueChanged(object sender, EventArgs e)
        {
            deptTreeList.Properties.Buttons[1].Visible = deptTreeList.EditValue != null;
            await LoadFirstPageAsync();
        }

        private void departmentTreeList_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1) deptTreeList.EditValue = null;
        }

        private async void BtnSearch_Click(object sender, EventArgs e)
        {
            await LoadFirstPageAsync();
        }

        private async void BtnReset_Click(object sender, EventArgs e)
        {
            Mutex.Begin(() => App.ContainerData.SetModel(layoutGroupFilter, SysRoleFilter.Default));
            await LoadFirstPageAsync();
        }
    }
}